package com.payment.ktb.activity.main1;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.payment.ktb.Interface.HttpCallbackListener;
import com.payment.ktb.R;
import com.payment.ktb.activity.BaseActivity;
import com.payment.ktb.constants.ConstantsUser;
import com.payment.ktb.constants.HttpActions;
import com.payment.ktb.constants.HttpUrls;
import com.payment.ktb.utils.AlertDialogUtils;
import com.payment.ktb.utils.HttpUtils;
import com.payment.ktb.utils.SharedPreferencesUtils;
import com.payment.ktb.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by admin on 2017/9/9.
 */

public class OrderConfirmNoBindCardActivity extends BaseActivity {

    @BindView(R.id.btn_orderconfirmnobindcard_obtaincode)
    Button btn_orderconfirmnobindcard_obtaincode;
    @BindView(R.id.tv_orderconfirmnobindcard_amount)
    TextView tv_orderconfirmnobindcard_amount;
    @BindView(R.id.et_orderconfirmnobindcard_accountName)
    EditText et_orderconfirmnobindcard_accountName;
    @BindView(R.id.et_orderconfirmnobindcard_usercert)
    EditText et_orderconfirmnobindcard_usercert;
    @BindView(R.id.tv_orderconfirmnobindcard_bankname)
    TextView tv_orderconfirmnobindcard_bankname;
    @BindView(R.id.tv_orderconfirmnobindcard_cardno)
    TextView tv_orderconfirmnobindcard_cardno;
    @BindView(R.id.et_orderconfirmnobindcard_phone)
    EditText et_orderconfirmnobindcard_phone;
    @BindView(R.id.et_orderconfirmnobindcard_cvv2)
    EditText et_orderconfirmnobindcard_cvv2;
    @BindView(R.id.et_orderconfirmnobindcard_cardyxq)
    EditText et_orderconfirmnobindcard_cardyxq;
    @BindView(R.id.et_orderconfirmnobindcard_code)
    EditText et_orderconfirmnobindcard_code;

    MyCountDownTimer countDownTimer;
    private long totalTime = 62000;
    private long intervalTime = 1000;
    private String linkId = String.valueOf(new Date().getTime());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_orderconfirmnobindcard);
        ButterKnife.bind(this);
        initTitle("订单确认");
        initData();
    }

    private void initData() {
        tv_orderconfirmnobindcard_amount.setText("¥ " + handleFen2Yuan(String.valueOf(Double.valueOf(getIntent().getStringExtra("amount")))));
        et_orderconfirmnobindcard_accountName.setText(SharedPreferencesUtils.getString(ConstantsUser.userAccount));
        et_orderconfirmnobindcard_usercert.setText(SharedPreferencesUtils.getString(ConstantsUser.userCert).substring(0,4) + "******" + SharedPreferencesUtils.getString(ConstantsUser.userCert).substring(SharedPreferencesUtils.getString(ConstantsUser.userCert).length() - 4));
        tv_orderconfirmnobindcard_bankname.setText(getIntent().getStringExtra("cardBank"));
        tv_orderconfirmnobindcard_cardno.setText(getIntent().getStringExtra("cardNo"));
        et_orderconfirmnobindcard_phone.setText(getIntent().getStringExtra("cardPhone"));
    }


    @OnClick({R.id.btn_orderconfirmnobindcard_obtaincode,R.id.btn_orderconfirmnobindcard_confrim,R.id.rl_orderconfirmnobindcard_deletephone})
    public void clickEvent(View view) {


        switch (view.getId()) {

            //获取验证码
            case R.id.btn_orderconfirmnobindcard_obtaincode:
                if (checkPassSmS()){
                    obtainMsgCode();
                }
                break;

            //确认
            case R.id.btn_orderconfirmnobindcard_confrim:

            if (checkPassSmS()) {
                if (!TextUtils.isEmpty(et_orderconfirmnobindcard_code.getText().toString())){
                    submit();
                }else {
                    ToastUtils.showToast("请输入验证码!");
                }}

                break;

            //删除电话号码
            case R.id.rl_orderconfirmnobindcard_deletephone:
            et_orderconfirmnobindcard_phone.setText("");
                break;

        }

    }


    //提交订单
    private void submit() {

        progressDialogUtils.showProgress();

        //构造传输参数
        Map<String, String> map = new HashMap<String,String>();
        map.put("orderNo",getIntent().getStringExtra("orderNo"));
        map.put("smsCode",et_orderconfirmnobindcard_code.getText().toString());

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.PayOrderNocardConfirm, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                progressDialogUtils.showProgress("正在查询订单状态...");
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getOrderStatus();
                    }
                },3000);
            }

            @Override
            public void onError(VolleyError volleyError) {
                progressDialogUtils.dismissProgress();
                AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());
            }
        });
    }

    private boolean checkPassSmS() {

        if (TextUtils.isEmpty(et_orderconfirmnobindcard_accountName.getText().toString())) {
            ToastUtils.showToast("请输入姓名!");
            return false;
        } else if (TextUtils.isEmpty(et_orderconfirmnobindcard_usercert.getText().toString())) {
            ToastUtils.showToast("请输入身份证号！");
            return false;
        } else if (TextUtils.isEmpty(et_orderconfirmnobindcard_phone.getText().toString())) {
            ToastUtils.showToast("请输入预留手机号！");
            return false;
        } else if (et_orderconfirmnobindcard_phone.getText().toString().length() != 11) {
            ToastUtils.showToast("请输入正确的手机号码！");
            return false;
        }else if (TextUtils.isEmpty(et_orderconfirmnobindcard_cvv2.getText().toString())) {
            ToastUtils.showToast("请输入安全码！");
            return false;
        }else if (et_orderconfirmnobindcard_cvv2.getText().toString().length() != 3) {
            ToastUtils.showToast("请输入正确的安全码！");
            return false;
        }else if (TextUtils.isEmpty(et_orderconfirmnobindcard_cardyxq.getText().toString())) {
            ToastUtils.showToast("请输入有效期！");
            return false;
        }else if (et_orderconfirmnobindcard_cardyxq.getText().toString().length() != 4) {
            ToastUtils.showToast("请输入正确的有效期！");
            return false;
        }
            return true;
    }

    /**
     * 获取注册的短信验证码
     */
    private void obtainMsgCode() {
        countDownTimer = new MyCountDownTimer(totalTime,intervalTime);
        countDownTimer.start();
        progressDialogUtils.showProgress();

        //构造传输参数
        //将参数放入map中
        HashMap<String, String> map = new HashMap<String,String>();
        map.put("orderNo",getIntent().getStringExtra("orderNo"));
        map.put("cardAccount",et_orderconfirmnobindcard_accountName.getText().toString());
        if (et_orderconfirmnobindcard_usercert.getText().toString().contains("*")) {
            map.put("cardCert",SharedPreferencesUtils.getString(ConstantsUser.userCert));
        }else {
            map.put("cardCert",et_orderconfirmnobindcard_usercert.getText().toString());
        }
        map.put("cardPhone",et_orderconfirmnobindcard_phone.getText().toString());
        map.put("cardCvv",et_orderconfirmnobindcard_cvv2.getText().toString());
        map.put("cardYxq",et_orderconfirmnobindcard_cardyxq.getText().toString());

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.PayOrderNocardSms, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                progressDialogUtils.dismissProgress();
                ToastUtils.showToast("获取验证码成功！");
            }

            @Override
            public void onError(VolleyError volleyError) {
                progressDialogUtils.dismissProgress();
                AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());
                countDownTimer.cancel();
                btn_orderconfirmnobindcard_obtaincode.setEnabled(true);
                btn_orderconfirmnobindcard_obtaincode.setText("重新获取");
            }
        });


    }





    private String handleFen2Yuan(String fen) {
        if (fen.equals("0")) {
            return "0.00";
        }
        double srcFen = Double.valueOf(fen);
        double roundSrcFen = Math.round(srcFen);
        return String.valueOf(roundSrcFen/100);
    }


    //查询订单状态
    public void getOrderStatus() {


        progressDialogUtils.showProgress("正在查询订单状态...");

        //构造传输参数
        final Map<String, String> map = new HashMap<String,String>();
        map.put("linkId",linkId);
        map.put("orderNo",getIntent().getStringExtra("orderNo"));

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.PayOrderStatus, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                progressDialogUtils.dismissProgress();
                try {
                    JSONObject jsonObject = new JSONObject(response);

                    Intent intent = null;

                    if (jsonObject.optString("orderStatus").equals("20")) {
                        intent = new Intent(mContext,OrderConfirmSuccessActivity.class);
                    }else if (jsonObject.optString("orderStatus").equals("21")){
                        intent = new Intent(mContext,OrderConfirmFailActivity.class);
                    }else {
                        intent = new Intent(mContext,OrderConfirmWaitActivity.class);
                    }
                    intent.putExtra("amount",getIntent().getStringExtra("amount"));

                    if ("1000".equals(jsonObject.optString("product"))) {
                      intent.putExtra("goodsName","商户收款");
                    }else if ("1001".equals(jsonObject.optString("product"))) {
                        intent.putExtra("goodsName","会员购买");
                    }else if ("1002".equals(jsonObject.optString("product"))) {
                        intent.putExtra("goodsName","后台管理费");
                    }else {
                        intent.putExtra("goodsName","商户收款");
                    }

                    intent.putExtra("cardBank",getIntent().getStringExtra("cardBank"));
                    intent.putExtra("cardNo",getIntent().getStringExtra("cardNo"));
                    intent.putExtra("orderNo",jsonObject.optString("orderNo"));
                    intent.putExtra("orderTime",jsonObject.optString("orderTime"));
                    intent.putExtra("ordermemo",jsonObject.optString("ordermemo"));
                    startActivity(intent);
                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }
            }

            @Override
            public void onError(VolleyError volleyError) {
                progressDialogUtils.dismissProgress();
                AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());
            }
        });

    }


    /**
     * 获取短信验证码的时候，显示倒计时
     */
    class MyCountDownTimer extends CountDownTimer {

        /**
         *
         * @param millisInFuture
         *            倒计时总时间
         * @param countDownInterval
         *            每隔多久触发onTick方法
         */
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onFinish() {
            btn_orderconfirmnobindcard_obtaincode.setText("重新获取");
            btn_orderconfirmnobindcard_obtaincode.setEnabled(true);
        }

        @Override
        public void onTick(long arg0) { // arg0 表示距离本级倒计时结束还有多长时间

            btn_orderconfirmnobindcard_obtaincode.setText("重新获取" + "(" + ((arg0 / 1000) -1) + ")" );
            btn_orderconfirmnobindcard_obtaincode.setEnabled(false);

        }

    }





}
